﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Diagnostics;
using System.Threading.Tasks;

namespace RB.Web.Security
{
    public class VarAuthorizationModule : IHttpModule
    {
        public void Dispose()
        {
            
        }

        public void Init(HttpApplication context)
        {
            context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        void context_AuthorizeRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpContext context = app.Context;

            if (!context.SkipAuthorization)
            {
                Debug.Print("AuthorizeRequest: " + context.Request.Url.AbsolutePath);

                bool authorized = VarAuthorization.Authorize(context);
                if (!authorized)
                {
                    HttpException ex = null;

                    if (context.Request.IsAuthenticated)
                    {
                        ex = new HttpException(401, "Unauthorized");
                        context.Response.StatusCode = 401;
                    }
                    else
                    {
                        ex = new HttpException(403, "Forbidden");
                        context.Response.StatusCode = 403;
                    }
                    context.Response.Write(ex.GetHtmlErrorMessage());
                    app.CompleteRequest();
                }
            }
        }

        void context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication app;
            HttpContext context;

            app = (HttpApplication)sender;
            context = app.Context;

            ////////////////////////////////////////////////////////////
            // Step 1: Check if we are using cookie authentication and
            //         if authentication failed
            if (context.Response.StatusCode != 401 && context.Response.StatusCode != 403)
                return;

            ////////////////////////////////////////////////////////////
            // Change 401 to a redirect to login page
            if (context.Response.StatusCode == 403)
                VarAuthentication.RedirectToLogin(context);
            else
                VarAuthorization.RedirectToAccessDenied(context);
        }
    }
}
